import { createRouter, createWebHistory } from 'vue-router'
import { useGlobalStore } from '@/stores'

/* Layout */
import Layout from '@/layout/index.vue'

// 不需要登录的页面
const constantRoutes: any[] = [
  {
    path: '/login',
    name: 'login',
    component: () => import('@/views/login/index.vue')
  }
]

// 侧边栏的页面
export const menuRoutes = [
  //  {
  //   path: '/home',
  //   name: 'Home',
  //   component: () => import('@/views/home/index.vue'),
  //   meta: {
  //     title: '首页',
  //     icon: 'home',
  //     requireAuth: true
  //   }
  // },
  {
    path: '/order',
    name: 'Order',
    component: () => import('@/views/order/index.vue'),
    meta: {
      title: '订单管理',
      icon: 'article',
      requireAuth: true
    }
  },
  {
    path: '/customer',
    name: 'Customer',
    component: () => import('@/views/customer/index.vue'),
    meta: {
      title: '客户管理',
      icon: 'article',
      requireAuth: true
    }
  },
  {
    path: '/employee',
    name: 'Employee',
    component: () => import('@/views/employee/index.vue'),
    meta: {
      title: '员工管理',
      icon: 'article',
      requireAuth: true
    }
  },
  {
    path: '/settings',
    name: 'Settings',
    component: () => import('@/views/settings/index.vue'),
    meta: {
      title: '基本设置',
      icon: 'article',
      requireAuth: true
    }
  }
]

const router = createRouter({
  history: createWebHistory(import.meta.env.BASE_URL),
  routes: [
    {
      path: '/',
      redirect: 'order',
      component: Layout,
      children: [...menuRoutes]
    },
    ...constantRoutes
  ]
})

export default router

// 全局守卫：登录拦截 本地没有存token,请重新登录
router.beforeEach((to, from, next) => {
  const store = useGlobalStore()
  if (!to.meta.requireAuth) return next()
  if (store.access_token) {
    next()
  } else {
    router.push('/login')
  }
})
